import { createDictionaryItem, deleteDictionaryItem, getDictionaryItems, updateDictionaryItem } from "@/api/dictionary";
import DetailWrap from "@/components/DetailWrap";
import DictionaryColumnRender from "@/components/DictionaryColumnRender";
import FormByData, { formatFormItem, FormItemType, FormTableItemType } from "@/components/FormByData/FormByData";
import Modal from "@/components/Modal/Modal";
import Search from "@/components/Search";
import Table, { TableRef } from "@/components/Table";
import TableSwitch from "@/components/TableSwitch";
import { AntTagColors, StatusOptions } from "@/constant/common";
import { DictionaryItem } from "@/typings/api";
import { Operation } from "@/typings/common";
import { EditOutlined } from "@ant-design/icons";
import { Button, FormInstance, message, Tag } from "antd";
import { useRef, useState } from "react";
import { useSearchParams } from "react-router-dom";

type SearchFields = Pick<DictionaryItem, "label" | "value">;
const DictionaryItems = () => {
    const [params] = useSearchParams();
    const _id = params.get("_id");

    const columns: FormTableItemType<DictionaryItem>[] = [
        { dataIndex: "label", title: "名字", required: true },
        { dataIndex: "value", title: "值", required: true },
        {
            dataIndex: "backgroundColor",
            title: "背景颜色",
            type: "autoComplete",
            options: Object.entries(AntTagColors).map(([value, label]) => ({
                label: (
                    <div className="w-full flex justify-between pr-2">
                        <Tag color={value}>{value}</Tag>
                        <div className="text-gray-500">{label}</div>
                    </div>
                ),
                value,
            })),
            render: value => value && <Tag color={value}>{value}</Tag>,
        },
        {
            dataIndex: "status",
            title: "状态",
            type: "radio",
            options: StatusOptions,
            render: (_, record) => (
                <TableSwitch dataIndex="status" record={record} updateRecord={updateDictionaryItem} getList={tableRef.current!.getList} />
            ),
        },
        { dataIndex: "sort", title: "序号", type: "inputNumber" },
        { dataIndex: "remark", title: "备注", type: "textarea" },
        { dataIndex: "operation", title: "操作", isForm: false },
    ];
    const [modalShow, setModalShow] = useState(false);
    const [opType, setOpType] = useState<Operation>("add");
    const currentRecord = useRef<DictionaryItem>();
    const formRef = useRef<FormInstance>();
    const tableRef = useRef<TableRef>(null);
    const [confirmLoading, setConfirmLoading] = useState(false);
    const handleAdd = () => {
        setOpType("add");
        setModalShow(true);
        formRef.current?.resetFields();
    };
    const handleEdit = (record: DictionaryItem) => {
        setOpType("edit");
        setModalShow(true);
        formRef.current?.resetFields();
        formRef.current?.setFieldsValue(record);
        currentRecord.current = record;
    };
    const submit = async () => {
        const formData = await formRef.current?.validateFields();
        setConfirmLoading(true);
        try {
            if (opType === "add") {
                await createDictionaryItem({ ...formData, dictionaryId: _id });
                message.success("创建成功");
            } else {
                if (!currentRecord.current) return;
                await updateDictionaryItem({ ...formData, _id: currentRecord.current._id });
                message.success("编辑成功");
            }
            setModalShow(false);
        } finally {
            setConfirmLoading(false);
        }
        tableRef.current?.getList();
    };

    const searchFormItems: FormItemType<SearchFields>[] = [
        { label: "名字", name: "label" },
        { label: "值", name: "value" },
    ];
    const searchParams = useRef<Partial<DictionaryItem>>({});
    const handleSearch = (formData: SearchFields) => {
        searchParams.current = formData;
        tableRef.current?.getList(1, 10);
    };

    const searchFromRef = useRef<FormInstance>();
    const handleReset = () => {
        searchFromRef.current?.resetFields();
        searchParams.current = {};
        tableRef.current?.getList(1, 10);
    };
    return (
        <DetailWrap
            title={
                <Search<SearchFields>
                    title="字典数据"
                    formItems={searchFormItems}
                    onReset={handleReset}
                    onAdd={handleAdd}
                    onSearch={handleSearch}
                    getFormRef={ref => (searchFromRef.current = ref)}
                />
            }
            backUrl="/system/dictionary"
        >
            <Table
                _id={_id}
                ref={tableRef}
                getApi={p => getDictionaryItems({ ...p, ...searchParams.current })}
                delApi={deleteDictionaryItem}
                columns={columns}
                actionMore={record => (
                    <Button icon={<EditOutlined />} size="small" onClick={() => handleEdit(record)}>
                        编辑
                    </Button>
                )}
            />
            <Modal
                title={`${opType === "add" ? "添加" : "编辑"}字典数据`}
                open={modalShow}
                onCancel={() => setModalShow(false)}
                forceRender
                onOk={submit}
                confirmLoading={confirmLoading}
            >
                <FormByData<DictionaryItem>
                    getFormRef={ref => (formRef.current = ref)}
                    cols={1}
                    formItems={formatFormItem(columns)}
                    formProps={{ initialValues: { status: true, sort: 100 } }}
                />
            </Modal>
        </DetailWrap>
    );
};

export default DictionaryItems;
